/* eslint-disable no-restricted-syntax */
/* eslint-disable no-param-reassign */
/* eslint-disable array-callback-return */
import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import {
  DownloadOutlined,
  DownOutlined,
  UpOutlined,
  QuestionCircleOutlined,
} from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {
  Row,
  Col,
  Card,
  Input,
  Button,
  Modal,
  message,
  Badge,
  DatePicker,
  Tabs,
  Select,
  Alert,
  Radio,
  Tooltip,
} from 'antd';
import Link from 'umi/link';
import router from 'umi/router';
import queryString from 'query-string';
import moment from 'moment';
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import ProTable from '@/pages/components/Problem/ProblemPage/ProTable';
import ProExportBtn from '@/pages/components/Problem/ProblemPage/ProExportBtn';
import Authorized from '@/utils/Authorized';
import styles from '@/utils/utils.less';
import downloadFile, { getProPagination } from '@/utils/utils';
import Customer from '../../components/SendOrderCustomer';
import Area from '../../components/Area';
import proIcon from '../../../assets/proIcon.png';
import TextOverFlow from '../../components/TextOverFlow';
import BatchTaskProgress from '../../components/BatchTaskProgress';

const RadioGroup = Radio.Group;
const FormItem = Form.Item;
const { TabPane } = Tabs;
const { RangePicker } = DatePicker;
const RadioButton = Radio.Button;
const { Option } = Select;
let interval = null;

@connect(({ addempsend, addemprec, loading, publicdata }) => ({
  pageData: addempsend.pageData,
  proPageData: addempsend.proPageData,
  supplyList: addemprec.supplyList,
  invoicemessage: addempsend.invoicemessage,
  dictCode: publicdata.dictCode,
  dataInfo: addempsend.detail || {},
  productList: addempsend.addOrEdit.productList,
  loading:
    loading.effects['addempsend/getBatchId'] || loading.effects['addempsend/getProgress']
      ? false
      : loading.models.addempsend,
  expandForm: addempsend.expandForm,
  activeKey: addempsend.activeKey,
  formFieldsValue: addempsend.formFieldsValue,
  addempsend,
  tabList: addempsend.tabList,
  downloadParams: addempsend.downloadParams,
}))
@Form.create()
class TableList extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      formValues: {},
      selectedRows: [],
      sleectedList: [],
      selectedRowKeys: [],
      editFlag: null, // 状态
      resultInfo: {
        // 结果数据必传
        batchName: '发单任务', // 任务名称
        taskCount: 0, // 导入数据
        successCount: 0, // 成功数据
        errorCount: 0, // 失败数据
        batchNo: '', // 批次号
        errorUrl: '/nsApi/sendAdd/export/error', // 下载错误信息地址
        errorParams: null, // 下载错误数据参数
      },
      progressVisible: false, // 进度弹框显隐
      isShowResult: false, // 进度完成
      taskSourceList: [], // 任务类型
      proTable: {},
    };
    this.tableSearchLayout = {
      labelCol: { md: { span: 7 } },
      wrapperCol: { md: { span: 17 } },
    };

    this.columns = [
      {
        title: '姓名',
        dataIndex: 'empName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: (text, record) =>
          record.probFlag === 1 ? (
            <Tooltip
              placement="top"
              title={
                <div>
                  <p>
                    问题人员类型：
                    {record.probDets && record.probDets[0] ? record.probDets[0].probTypeName : '--'}
                  </p>
                  <p>
                    问题说明：
                    {record.probDets && record.probDets[0] ? record.probDets[0].probTypeDesc : '--'}
                  </p>
                </div>
              }
            >
              <span>
                {text}
                <img src={proIcon} alt="问题人员" />
              </span>
            </Tooltip>
          ) : (
            <span>{text}</span>
          ),
      },
      {
        title: '客户名称',
        dataIndex: 'custName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => <TextOverFlow text={text} />,
      },
      {
        title: '执行地区',
        dataIndex: 'cityName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '任务类型',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        dataIndex: 'taskSourceName',
      },
      {
        title: '操作时间',
        dataIndex: 'operTime',
        // sorter: true,
        sorter: (a, b) => new Date(b.operTime) - new Date(a.operTime),
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: val => (val && moment(val).format('YYYY-MM-DD HH:mm')) || '--',
      },
      {
        title: '操作',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', width: 150, textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'center' } }),
        render: (text, record) => (
          <Link
            to={`/sendordermanage/addemployee/detail?sendOrdAddTaskId=${record.sendOrdAddTaskId}`}
          >
            查看
          </Link>
        ),
      },
    ];
    this.columnstwo = [
      {
        title: '姓名',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        dataIndex: 'empName',
        render: (text, record) =>
          record.probFlag === 1 ? (
            <Tooltip
              placement="top"
              title={
                <div>
                  <p>
                    问题人员类型：
                    {record.probDets && record.probDets[0] ? record.probDets[0].probTypeName : '--'}
                  </p>
                  <p>
                    问题说明：
                    {record.probDets && record.probDets[0] ? record.probDets[0].probTypeDesc : '--'}
                  </p>
                </div>
              }
            >
              <span>
                {text}
                <img src={proIcon} alt="问题人员" />
              </span>
            </Tooltip>
          ) : (
            <span>{text}</span>
          ),
      },
      {
        title: '客户名称',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        dataIndex: 'custName',
        render: text => <TextOverFlow text={text} />,
      },
      {
        title: '执行地区',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        dataIndex: 'cityName',
      },
      {
        title: '接单方',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        dataIndex: 'recvSuppName',
        render: text => <TextOverFlow text={text} />,
      },

      {
        title: '协议名称',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        dataIndex: 'suppProtName',
        render: text => <TextOverFlow text={text} />,
      },
      {
        title: '任务类型',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        dataIndex: 'taskSourceName',
      },
      {
        title: '发单时间',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        dataIndex: 'sendTime',
        sorter: (a, b) => new Date(b.sendTime) - new Date(a.sendTime),
        render: val => (val && moment(val).format('YYYY-MM-DD HH:mm')) || '--',
      },
      {
        title: '操作',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', width: 150, textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'center' } }),
        render: (text, record) => (
          <Link
            to={`/sendordermanage/addemployee/detail?sendOrdAddTaskId=${record.sendOrdAddTaskId}`}
          >
            查看
          </Link>
        ),
      },
    ];
    this.columnsthree = [
      {
        title: '姓名',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        dataIndex: 'empName',
        render: (text, record) =>
          record.probFlag === 1 ? (
            <Tooltip
              placement="top"
              title={
                <div>
                  <p>
                    问题人员类型：
                    {record.probDets && record.probDets[0] ? record.probDets[0].probTypeName : '--'}
                  </p>
                  <p>
                    问题说明：
                    {record.probDets && record.probDets[0] ? record.probDets[0].probTypeDesc : '--'}
                  </p>
                </div>
              }
            >
              <span>
                {text}
                <img src={proIcon} alt="问题人员" />
              </span>
            </Tooltip>
          ) : (
            <span>{text}</span>
          ),
      },
      {
        title: '客户名称',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        dataIndex: 'custName',
        render: text => <TextOverFlow text={text} />,
      },
      {
        title: '执行地区',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        dataIndex: 'cityName',
      },
      {
        title: '接单方',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        dataIndex: 'recvSuppName',
        render: text => <TextOverFlow text={text} />,
      },

      {
        title: '协议名称',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        dataIndex: 'suppProtName',
        render: text => <TextOverFlow text={text} />,
      },
      {
        title: '任务类型',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        dataIndex: 'taskSourceName',
      },
      {
        title: '接单时间',
        dataIndex: 'operTime',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        sorter: (a, b) => new Date(b.operTime) - new Date(a.operTime),
        render: val => (val && moment(val).format('YYYY-MM-DD HH:mm')) || '--',
      },
      {
        title: '操作',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', width: 150, textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'center' } }),
        render: (text, record) => (
          <Link
            to={`/sendordermanage/addemployee/detail?sendOrdAddTaskId=${
              record.sendOrdAddTaskId
              // eslint-disable-next-line react/destructuring-assignment
            }&activeKey=${this.props.activeKey}`}
          >
            查看
          </Link>
        ),
      },
    ];
    this.columnsfour = [
      {
        title: '姓名',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        dataIndex: 'empName',
        render: (text, record) =>
          record.probFlag === 1 ? (
            <Tooltip
              placement="top"
              title={
                <div>
                  <p>
                    问题人员类型：
                    {record.probDets && record.probDets[0] ? record.probDets[0].probTypeName : '--'}
                  </p>
                  <p>
                    问题说明：
                    {record.probDets && record.probDets[0] ? record.probDets[0].probTypeDesc : '--'}
                  </p>
                </div>
              }
            >
              <span>
                {text}
                <img src={proIcon} alt="问题人员" />
              </span>
            </Tooltip>
          ) : (
            <span>{text}</span>
          ),
      },
      {
        title: '客户名称',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        dataIndex: 'custName',
        render: text => <TextOverFlow text={text} />,
      },
      {
        title: '执行地区',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        dataIndex: 'cityName',
      },
      {
        title: '接单方',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        dataIndex: 'recvSuppName',
        render: text => <TextOverFlow text={text} />,
      },

      {
        title: '协议名称',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        dataIndex: 'suppProtName',
        render: text => <TextOverFlow text={text} />,
      },
      {
        title: '任务类型',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        dataIndex: 'taskSourceName',
      },
      {
        title: '有无修改',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        dataIndex: 'editFlagName',
        sorter: true,
      },
      {
        title: '回单时间',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        dataIndex: 'returnTime',
        sorter: (a, b) => new Date(b.returnTime) - new Date(a.returnTime),
        render: val => (val && moment(val).format('YYYY-MM-DD HH:mm')) || '--',
      },
      {
        title: '操作',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', width: 150, textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'center' } }),
        render: (text, record) => (
          <Link
            to={`/sendordermanage/addemployee/detail?sendOrdAddTaskId=${
              record.sendOrdAddTaskId
              // eslint-disable-next-line react/destructuring-assignment
            }&activeKey=${this.props.activeKey}`}
          >
            查看
          </Link>
        ),
      },
    ];
    // this.columnsfive = [
    //   {
    //     title: '姓名',
    //     onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
    //     dataIndex: 'empName',
    //   },
    //   {
    //     title: '证件号',
    //     onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
    //     dataIndex: 'idCode',
    //   },
    //   {
    //     title: '客户名称',
    //     onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
    //     dataIndex: 'custName',
    //     render: text => <TextOverFlow text={text} />,
    //   },
    //   {
    //     title: '接单方',
    //     onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
    //     dataIndex: 'recvSuppName',
    //     render: text => <TextOverFlow text={text} />,
    //   },

    //   {
    //     title: '问题对象',
    //     onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
    //     dataIndex: 'probObj',
    //   },

    //   {
    //     title: '问题类型',
    //     onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
    //     dataIndex: 'probTypeIdName',
    //   },
    //   {
    //     title: '操作',
    //     onHeaderCell: () => ({ style: { fontWeight: 'bold', width: 150, textAlign: 'center' } }),
    //     onCell: () => ({ style: { textAlign: 'center' } }),
    //     render: (text, record) => (
    //       <Link to={`/sendordermanage/addemployee/proDetail?detId=${record.detId}`}>查看</Link>
    //     ),
    //   },
    // ];
    this.columnssix = [
      {
        title: '姓名',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        dataIndex: 'empName',
        render: (text, record) =>
          record.probFlag === 1 ? (
            <Tooltip
              placement="top"
              title={
                <div>
                  <p>
                    问题人员类型：
                    {record.probDets && record.probDets[0] ? record.probDets[0].probTypeName : '--'}
                  </p>
                  <p>
                    问题说明：
                    {record.probDets && record.probDets[0] ? record.probDets[0].probTypeDesc : '--'}
                  </p>
                </div>
              }
            >
              <span>
                {text}
                <img src={proIcon} alt="问题人员" />
              </span>
            </Tooltip>
          ) : (
            <span>{text}</span>
          ),
      },
      {
        title: '证件号',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        dataIndex: 'idCode',
      },
      {
        title: '客户名称',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        dataIndex: 'custName',
        render: text => <TextOverFlow text={text} />,
      },
      {
        title: '执行地区',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        dataIndex: 'cityName',
      },
      {
        title: '接单方',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        dataIndex: 'recvSuppName',
        render: text => <TextOverFlow text={text} />,
      },
      {
        title: '任务类型',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        dataIndex: 'taskSourceName',
      },
      {
        title: '取消时间',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        dataIndex: 'cancelTime',
        sorter: true,
        render: val => (val && moment(val).format('YYYY-MM-DD HH:mm')) || '--',
      },
      {
        title: '操作',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', width: 150, textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'center' } }),
        render: (text, record) => (
          <Link
            to={`/sendordermanage/addemployee/detail?sendOrdAddTaskId=${record.sendOrdAddTaskId}`}
          >
            查看
          </Link>
        ),
      },
    ];
  }

  componentDidMount() {
    const {
      pageData: { pagination },
      location,
      activeKey,
      dispatch,
    } = this.props;
    const { isMenuLink } = queryString.parse(location.search);

    const tempActiveKey = queryString.parse(location.search).activeKey || activeKey;

    dispatch({
      type: 'addempsend/updateModalData',
      payload: {
        activeKey: tempActiveKey,
        proBaseList: {},
        proFbList: [],
      },
    });

    dispatch({
      type: 'publicdata/fetchDictCode',
      payload: ['SEND_TASK_SOURCE'],
    }).then(data => {
      let taskSourceList = [];
      if (data && data.SEND_TASK_SOURCE && data.SEND_TASK_SOURCE.length) {
        taskSourceList = data.SEND_TASK_SOURCE.filter(
          item =>
            item.itemCode !== '2' &&
            item.itemCode !== '3' &&
            item.itemCode !== '4' &&
            item.itemCode !== '5' &&
            item.itemCode !== '7' &&
            item.itemCode !== '8' &&
            item.itemCode !== '9' &&
            item.itemCode !== '11'
        );
      }
      this.setState({ taskSourceList });
    });
    const proPagination = getProPagination(tempActiveKey, '5', pagination);
    if (isMenuLink) {
      this.resetAndGeLlist(location);
    } else {
      this.getList(tempActiveKey, proPagination.current, proPagination.pageSize);
    }
    // this.getList();
    this.getDict();
  }

  componentWillUnmount() {
    clearInterval(interval);
  }

  // 查看当前有无任务
  checkHasTask = () => {
    const { dispatch } = this.props;
    // 查看当前有无任务进行
    dispatch({
      type: 'addempsend/checkHasTask',
    });
  };

  // 查询任务进度
  viewTaskProgress = () => {
    const {
      dispatch,
      addempsend: { batchId },
    } = this.props;
    const { resultInfo } = this.state;
    this.handleProgressModalVisible(true);
    dispatch({
      type: 'addempsend/updateModelData',
      payload: { progressPercent: 0 },
    });
    interval = setInterval(() => {
      dispatch({
        type: 'addempsend/getProgress',
        payload: { batchId },
      }).then(res => {
        if (res.success && res.data && res.data.successProp === 100) {
          // 完成
          clearInterval(interval);
          resultInfo.errorParams = {
            batchId: res.data.batchId,
          };
          this.setState({
            resultInfo: { ...resultInfo, ...res.data },
            isShowResult: true,
          });
        } else if (!res.success) {
          // 服务端异常
          clearInterval(interval);
          message.warning(`${res.message || '发单失败！'}`);
          this.handleProgressModalVisible(false);
        }
      });
    }, 1000);
  };

  // 进度弹框显隐
  handleProgressModalVisible = flag => {
    const {
      activeKey,
      pageData: { pagination },
    } = this.props;
    this.setState({
      progressVisible: !!flag,
    });
    if (!flag) {
      clearInterval(interval);
      this.getList(activeKey, pagination.current, pagination.pageSize);
    }
  };

  getDict = () => {
    const { dispatch, params } = this.props;
    dispatch({
      type: 'addemprec/fetchSupplyList',
      payload: { name: null, ...params },
    });
  };

  // 获取客户的下拉
  getCustList = e => {
    const { dispatch } = this.props;
    dispatch({
      type: 'addemprec/getcustNamesList',
      payload: {
        suppId: e,
      },
    });
  };

  getsuppId = e => {
    const { supplyList, form } = this.props;
    form.resetFields(['custId']);
    supplyList.map(item => {
      if (item.suppId === e) {
        this.getCustList(item.suppId);
      }
    });
  };

  // 获取列表
  getList = (activeKey = '1', currentPage = 1, pageSize = 10, queryParam, isClear = true) => {
    if (isClear) {
      this.setState({ sleectedList: [], selectedRows: [], selectedRowKeys: [] });
    }
    const { dispatch, form } = this.props;
    const { editFlag } = this.state;
    dispatch({
      type: 'addempsend/updateModelData',
      payload: { activeKey },
    });
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      // eslint-disable-next-line no-param-reassign
      fieldsValue = queryParam || fieldsValue;

      // eslint-disable-next-line no-restricted-syntax
      for (const key in fieldsValue) {
        if (key === 'createTime') {
          fieldsValue.operTimeStart =
            (fieldsValue.createTime &&
              fieldsValue.createTime[0] &&
              fieldsValue.createTime[0].format('YYYY-MM-DD')) ||
            null;
          fieldsValue.operTimeEnd =
            (fieldsValue.createTime &&
              fieldsValue.createTime[1] &&
              fieldsValue.createTime[1].format('YYYY-MM-DD')) ||
            null;
          delete fieldsValue[key];
        } else if (key === 'cityId' || key === 'custId') {
          fieldsValue[key] = fieldsValue[key] && fieldsValue[key].key;
        } else if (key === 'empName' || key === 'idCode') {
          fieldsValue[key] = (fieldsValue[key] && fieldsValue[key].trim()) || null;
        } else {
          fieldsValue[key] = fieldsValue[key] === undefined ? null : fieldsValue[key];
        }
      }
      const pageArg = { currentPage, pageSize };
      let values = {};
      if (activeKey === '4') {
        values = {
          ...fieldsValue,
          pageArg,
          busiType: 1,
          hdlState: activeKey,
          editFlag,
        };
      } else {
        values = {
          ...fieldsValue,
          pageArg,
          busiType: 1,
          hdlState: activeKey,
        };
      }
      fieldsValue.taskSource = (fieldsValue.taskSource && Number(fieldsValue.taskSource)) || null;
      values.taskSource = (values.taskSource && Number(values.taskSource)) || null;
      // if (activeKey === '5') {
      //   dispatch({
      //     type: 'addempsend/fetchProList',
      //     payload: {
      //       ...fieldsValue,
      //       pageArg,
      //       busiType: 1,
      //     },
      //   });
      // } else {
      //   dispatch({
      //     type: 'addempsend/fetchList',
      //     payload: values,
      //   });
      // }
      const downloadParams = {
        ...fieldsValue,
        busiType: 11,
        hdlState: activeKey,
        editFlag,
      };
      dispatch({
        type: 'addempsend/updateModelData',
        payload: {
          downloadParams,
        },
      });
      if (activeKey && Number(activeKey) === 5) {
        setTimeout(() => {
          const { proTable } = this.state;
          const proFormFieldsValue = { ...fieldsValue, busiType: 11, pageArg };
          if (proTable.searchList) {
            proTable.searchList(proFormFieldsValue, currentPage, pageSize);
          }
        });
      } else {
        dispatch({
          type: 'addempsend/fetchList',
          payload: values,
        });
      }
      if (activeKey === '1') {
        dispatch({
          type: 'addempsend/associatedNumber',
          payload: values,
        });
      }
      this.setState({
        formValues: values,
      });
    });
  };

  // 搜索时
  handleSearch = e => {
    if (e) e.preventDefault();
    const {
      dispatch,
      form,
      pageData: {
        pagination: { current, pageSize },
      },
      activeKey,
      tabList,
    } = this.props;
    const { editFlag } = this.state;
    this.setState({
      sleectedList: [],
      selectedRows: [],
      selectedRowKeys: [],
    });
    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const formsValue = {};
      // eslint-disable-next-line guard-for-in
      for (const key in fieldsValue) {
        formsValue[key] = fieldsValue[key] === undefined ? undefined : fieldsValue[key];
        if (key === 'createTime') {
          fieldsValue.operTimeStart =
            (fieldsValue.createTime &&
              fieldsValue.createTime[0] &&
              fieldsValue.createTime[0].format('YYYY-MM-DD')) ||
            null;
          fieldsValue.operTimeEnd =
            (fieldsValue.createTime &&
              fieldsValue.createTime[1] &&
              fieldsValue.createTime[1].format('YYYY-MM-DD')) ||
            null;
          delete fieldsValue[key];
        } else if (key === 'cityId' || key === 'custId') {
          fieldsValue[key] = fieldsValue[key] && fieldsValue[key].key;
        } else if (key === 'empName' || key === 'idCode') {
          fieldsValue[key] = fieldsValue[key] && fieldsValue[key].trim();
        } else {
          fieldsValue[key] = fieldsValue[key] === undefined ? undefined : fieldsValue[key];
        }
      }
      dispatch({
        type: 'addempsend/updateModalData',
        payload: {
          activeKey,
          formFieldsValue: formsValue,
        },
      });
      const pageArg = { currentPage: current, pageSize };
      let values = {};

      if (activeKey === '4') {
        values = {
          ...fieldsValue,
          pageArg,
          busiType: 1,
          hdlState: activeKey,
          editFlag,
        };
        const downloadParams = {
          ...fieldsValue,
          busiType: 11,
          hdlState: activeKey,
          editFlag,
        };
        dispatch({
          type: 'addempsend/updateModelData',
          payload: {
            downloadParams,
          },
        });
      } else {
        values = {
          ...fieldsValue,
          pageArg,
          busiType: 1,
          hdlState: activeKey,
        };
      }
      values.taskSource = (values.taskSource && Number(values.taskSource)) || null;
      let istag = null;
      for (const i in fieldsValue) {
        if (fieldsValue[i]) {
          istag = 1;
        }
      }
      if (istag === 1) {
        dispatch({
          type: 'addempsend/getTagData',
          payload: values,
        });
      } else {
        tabList.map(item => {
          item.isHas = false;
        });
        dispatch({
          type: 'addempsend/updateModalData',
          payload: { tabList },
        });
      }

      this.setState({ formValues: values });
      // if (!checkHasValue) {
      if (activeKey === '5') {
        const downloadParams = {
          ...fieldsValue,
          busiType: 11,
          hdlState: activeKey,
          editFlag,
        };
        dispatch({
          type: 'addempsend/updateModelData',
          payload: {
            downloadParams,
          },
        });
        setTimeout(() => {
          const { proTable } = this.state;
          const proFormFieldsValue = { ...fieldsValue, busiType: 11, pageArg };
          if (proTable.searchList) {
            proTable.searchList(proFormFieldsValue);
          }
        });
      } else {
        dispatch({
          type: 'addempsend/fetchList',
          payload: values,
        });
      }
      if (activeKey === '1') {
        dispatch({
          type: 'addempsend/associatedNumber',
          payload: values,
        });
      }
    });
  };

  // 重置
  handleFormReset = () => {
    const { form, dispatch } = this.props;
    dispatch({
      type: 'addempsend/updateModalData',
      payload: {
        formFieldsValue: {},
      },
    });
    form.resetFields();
    form.setFieldsValue({ createTime: null });
  };

  // 切换表格展开收起
  toggleForm = () => {
    const { expandForm, dispatch } = this.props;
    dispatch({
      type: 'addempsend/updateModalData',
      payload: {
        expandForm: !expandForm,
      },
    });
  };

  // 点击复选框
  handleSelectRows = (rows, selectedRowKeys) => {
    const sendOrList = [];
    this.setState({
      sleectedList: rows,
    });
    rows.map(item => {
      sendOrList.push(item.sendOrdAddTaskId || item.probDetId || item.detId);
    });
    this.setState({ selectedRows: sendOrList, selectedRowKeys });
  };

  // 有无修改
  saculo = e => {
    e.preventDefault();
    const hadlel = e == null ? null : e.target.value;
    this.setState(
      {
        editFlag: hadlel,
      },
      () => {
        this.getList('4');
      }
    );
  };

  // 导出
  export = () => {
    const { selectedRows } = this.state;
    if (!selectedRows.length) {
      Modal.confirm({
        icon: <QuestionCircleOutlined />,
        title: '温馨提示',
        content: '如果不选择列表数据，则默认导出当前条件下所有数据',
        okText: '导出',
        cancelText: '取消',
        onOk: () => {
          this.exportExcel();
        },
      });
    } else {
      this.exportExcel();
    }
  };

  // 导出excel
  exportExcel = () => {
    const { activeKey } = this.props;
    const { selectedRows, formValues } = this.state;
    delete formValues.pageArg;
    if (activeKey !== '5') {
      const pames = {
        sendAddTaskIds: (selectedRows.length && selectedRows) || null,
        hdlState: activeKey,
        ...formValues,
      };
      downloadFile(pames, '/nsApi/sendAdd/export', 'POST');
    } else {
      // 问题人员
      const pames = {
        detIds: (selectedRows.length && selectedRows) || null,
        hdlState: activeKey,
        ...formValues,
        busiType: 1,
      };
      downloadFile(pames, '/nsApi/sendProb/export', 'POST');
    }
  };

  // // 发单：选择数据
  // invoice = () => {
  //   const { selectedRowKeys, formValues } = this.state;
  //   delete formValues.pageArg;
  //   if (selectedRowKeys.length) {
  //     this.sendOrder({ sendAddTaskIds: selectedRowKeys });
  //   } else {
  //     Modal.confirm({icon: <QuestionCircleOutlined />,
  //       title: '温馨提示',
  //       content: '请选择数据，如不选择，默认发单当前条件下所有数据！',
  //       okText: '发单',
  //       cancelText: '取消',
  //       onOk: () => {
  //         this.sendOrder({ ...formValues });
  //       },
  //     });
  //   }
  // };

  // // 发单
  // sendOrder = params => {
  //   const { dispatch } = this.props;
  //   dispatch({
  //     type: 'addempsend/getBatchId',
  //     payload: params,
  //   }).then(response => {
  //     if (response.success) {
  //       this.setState({ isShowResult: false });
  //       this.viewTaskProgress();
  //     } else {
  //       message.warning(`${response.message || '服务端错误：获取批量任务失败！'}`);
  //     }
  //   });
  // };

  // 取消发单
  cancelSend = () => {
    const { selectedRowKeys } = this.state;
    const {
      dispatch,
      activeKey,
      pageData: { pagination },
    } = this.props;
    if (selectedRowKeys.length) {
      Modal.confirm({
        icon: <QuestionCircleOutlined />,
        title: `你确定要取消发单吗？`,
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
          dispatch({
            type: 'addempsend/cancelSend',
            payload: { sendOrdAddTaskId: selectedRowKeys },
          }).then(response => {
            if (response.success) {
              this.getList(activeKey, pagination.current, pagination.pageSize);
              message.success('取消发单成功！');
            } else {
              message.warning(`${response.message || '取消发单失败！'}`);
            }
          });
        },
      });
    } else {
      message.warning('请至少选择一条数据！');
    }
  };

  // 表格有变化：比如：切换页码
  handleStandardTableChange = pagination => {
    const { activeKey } = this.props;
    this.getList(activeKey, pagination.current, pagination.pageSize, undefined, false);
  };

  // 更改状态:废弃
  updateStatus = suppProtId => {
    const { dispatch } = this.props;
    Modal.confirm({
      icon: <QuestionCircleOutlined />,
      title: `你确定要废弃此协议吗？`,
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        dispatch({
          type: 'addempsend/updateStatus',
          payload: { suppProtId },
          callback: response => {
            if (response.success) {
              this.handleSearch();
              message.success('废弃成功！');
            } else {
              message.warning('废弃失败!');
            }
          },
        });
      },
    });
  };

  // 获取产品下拉数据
  getProductList = (suppId, areaIdList) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'addempsend/fetchProductList',
      payload: { suppId, areaIdList },
    });
  };

  getData = (value, id) => {
    const { form } = this.props;
    if (id) {
      form.setFieldsValue({ [id]: value });
      this.setState({ [id]: value });
    }
  };

  // 切换页签
  changeTabPane = activeKey => {
    const { dispatch, location, form } = this.props;
    router.push({
      pathname: location.pathname,
      query: {
        activeKey,
      },
    });
    const fieldsValue = form.getFieldsValue();
    dispatch({
      type: 'addempsend/updateTabListQuery',
      payload: {
        activeKey,
        formFieldsValue: fieldsValue,
      },
    });

    this.setState({ selectedRows: [], selectedRowKeys: [], sleectedList: [] }, () => {
      this.getList(activeKey);
    });
  };

  // 点击发单
  goAssociation = () => {
    const { dispatch, form } = this.props;
    const { selectedRowKeys, sleectedList } = this.state;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const formsValue = {};
      // eslint-disable-next-line guard-for-in
      for (const key in fieldsValue) {
        if (key === 'createTime') {
          fieldsValue.operTimeStart =
            (fieldsValue.createTime &&
              fieldsValue.createTime[0] &&
              fieldsValue.createTime[0].format('YYYY-MM-DD')) ||
            null;
          fieldsValue.operTimeEnd =
            (fieldsValue.createTime &&
              fieldsValue.createTime[1] &&
              fieldsValue.createTime[1].format('YYYY-MM-DD')) ||
            null;
          delete fieldsValue[key];
        } else {
          fieldsValue[key] = fieldsValue[key] === undefined ? null : fieldsValue[key];
        }
        // eslint-disable-next-line no-shadow
        Object.keys(fieldsValue).forEach(key => {
          formsValue[key] = fieldsValue[key] === undefined ? null : fieldsValue[key];
        });
      }
      dispatch({
        type: 'addempsend/updateModalData',
        payload: {
          formFieldsValue: formsValue,
          selectRowKeys: selectedRowKeys,
          selectRows: sleectedList,
        },
      });
      router.push('/sendordermanage/addemployee/association');
    });
  };

  // 查看客户关联情况
  checkAssoDetail = () => {
    router.push('/sendordermanage/addemployee/associationdetail');
  };

  async resetAndGeLlist(location) {
    const { dispatch, tabList } = this.props;
    const { queryParam } = location;
    if (queryParam) {
      await dispatch({
        type: 'addempsend/updateModalData',
        payload: {
          expandForm: true,
        },
      });
    } else {
      const newTabList = tabList.map(item => ({ ...item, isHas: false }));
      dispatch({
        type: 'addempsend/updateModalData',
        payload: { expandForm: false, tabList: newTabList },
      });
    }
    await this.handleFormReset();
    await this.getList(location.query.activeKey, undefined, undefined, queryParam);
    dispatch({
      type: 'global/changeIsMenuLink',
      payload: location,
    });
  }

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
      supplyList,
      formFieldsValue,
    } = this.props;
    return (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="接单方" {...this.tableSearchLayout}>
              {getFieldDecorator('recvSuppId', {
                initialValue: formFieldsValue.recvSuppId || undefined,
              })(
                // <Supplier allowClear params={{ status: 2 }} />
                <Select
                  placeholder="请输入关键字检索"
                  showSearch
                  optionFilterProp="children"
                  notFoundContent="暂无数据"
                  onSelect={(value, options) => this.getData(value, options)}
                  // onChange={this.getsuppId}
                  allowClear
                >
                  {supplyList.map(item => (
                    <Option key={item.suppId} title={item.name}>
                      {item.name}
                    </Option>
                  ))}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem {...this.tableSearchLayout} label="执行地区">
              {getFieldDecorator('cityId', {
                initialValue: formFieldsValue.cityId || undefined,
              })(<Area allowClear labelInValue />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Authorized authority="ns:sendAdd:page" noMatch={null}>
                <Button type="primary" onClick={this.handleSearch}>
                  查询
                </Button>
              </Authorized>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
              <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                展开 <DownOutlined />
              </a>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderAdvancedForm() {
    const {
      form: { getFieldDecorator },
      supplyList,
      formFieldsValue,
    } = this.props;
    const { taskSourceList } = this.state;
    return (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem {...this.tableSearchLayout} label="接单方">
              {getFieldDecorator('recvSuppId', {
                initialValue: formFieldsValue.recvSuppId || undefined,
              })(
                // <Supplier allowClear params={{ status: 2 }} />
                <Select
                  placeholder="请输入关键字检索"
                  showSearch
                  optionFilterProp="children"
                  notFoundContent="暂无数据"
                  onSelect={(value, options) => this.getData(value, options)}
                  // onChange={this.getsuppId}
                  allowClear
                >
                  {supplyList.map(item => (
                    <Option key={item.suppId} title={item.name}>
                      {item.name}
                    </Option>
                  ))}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem {...this.tableSearchLayout} label="执行地区">
              {getFieldDecorator('cityId', {
                initialValue: formFieldsValue.cityId || undefined,
              })(<Area allowClear labelInValue />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem {...this.tableSearchLayout} label="客户名称">
              {getFieldDecorator('custId', {
                rules: [{ required: false }],
                initialValue: formFieldsValue.custId || undefined,
              })(<Customer allowClear labelInValue />)}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem {...this.tableSearchLayout} label="姓名">
              {getFieldDecorator('empName', {
                initialValue: formFieldsValue.empName || undefined,
                rules: [{ required: false }],
              })(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem {...this.tableSearchLayout} label="证件号">
              {getFieldDecorator('idCode', {
                initialValue: formFieldsValue.idCode || undefined,
              })(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem {...this.tableSearchLayout} label="任务类型">
              {getFieldDecorator('taskSource', {
                initialValue: formFieldsValue.taskSource || undefined,
              })(
                <Select placeholder="请选择" showSearch optionFilterProp="children" allowClear>
                  {taskSourceList.map(item => (
                    <Option key={item.itemCode}>{item.itemName}</Option>
                  ))}
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem {...this.tableSearchLayout} label="操作时间">
              {getFieldDecorator('createTime', {
                initialValue: formFieldsValue.createTime || undefined,
              })(
                <RangePicker
                  placeholder={['操作开始日期', '操作结束日期']}
                  style={{ width: '100%' }}
                  format="YYYY-MM-DD"
                />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24} />
          <Col md={8} sm={24}>
            <div style={{ overflow: 'hidden' }}>
              <div style={{ float: 'right', marginBottom: 16 }}>
                <Button type="primary" onClick={this.handleSearch}>
                  查询
                </Button>
                <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                  重置
                </Button>
                <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                  收起
                  <UpOutlined />
                </a>
              </div>
            </div>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    const { expandForm } = this.props;

    return expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
  }

  render() {
    // const { pageData, loading, addempsend, tabList, activeKey, proPageData } = this.props;
    const { pageData, loading, addempsend, tabList, activeKey, downloadParams } = this.props;
    const {
      selectedRowKeys,
      editFlag,
      sleectedList,
      progressVisible,
      isShowResult,
      resultInfo,
    } = this.state;
    // 待发单
    const customerCharge = (
      <div>
        <Row style={{ marginBottom: '16px' }}>
          <Col md={12} sm={24}>
            <Authorized authority="ns:sendAdd:pushTask" noMatch={null}>
              <Button
                type="primary"
                style={{ marginRight: '8px' }}
                // onClick={() => {
                //   this.invoice();
                // }}
                onClick={() => {
                  this.goAssociation();
                }}
              >
                发单
              </Button>
            </Authorized>
            <Authorized authority="ns:sendAdd:export" noMatch={null}>
              <Button
                icon={<DownloadOutlined />}
                onClick={() => {
                  this.export();
                }}
              >
                导出
              </Button>
            </Authorized>
            {addempsend.isHasTask ? (
              <Alert
                style={{ margin: '16px 0 15px 0' }}
                message={
                  <span>
                    您有正在生成账单的任务
                    <a style={{ marginLeft: 20 }} onClick={() => this.viewTaskProgress(true)}>
                      查看
                    </a>
                  </span>
                }
                type="warning"
                showIcon
              />
            ) : (
              addempsend.peopleNumber && (
                <div style={{ margin: '16px 16px 0 0	', width: '200%' }}>
                  <Alert
                    message={
                      <Fragment>
                        客户数量
                        <a style={{ margin: '0 20px' }}>
                          {addempsend.peopleNumber.custAmount
                            ? addempsend.peopleNumber.custAmount
                            : 0}
                        </a>
                        已关联人数
                        <a style={{ margin: '0 20px' }}>
                          {addempsend.peopleNumber.matchAmount
                            ? addempsend.peopleNumber.matchAmount
                            : 0}
                        </a>
                        未关联人数
                        <a style={{ margin: '0 20px' }}>
                          {addempsend.peopleNumber.noMatchAmount
                            ? addempsend.peopleNumber.noMatchAmount
                            : 0}
                        </a>
                        {/* {addempsend.peopleNumber && addempsend.peopleNumber.noMatchAmount > 0 ? (
                          <a onClick={() => this.goAssociation()}>去关联协议</a>
                        ) : null} */}
                        <a
                          style={{ position: 'absolute', right: 15 }}
                          onClick={() => this.checkAssoDetail()}
                        >
                          查看客户关联情况
                        </a>
                      </Fragment>
                    }
                    type="info"
                    showIcon
                  />
                </div>
              )
            )}
          </Col>
        </Row>
        <StandardTable
          selectedRows={sleectedList}
          selectedRowKeys={selectedRowKeys}
          loading={loading}
          data={pageData}
          rowKey="sendOrdAddTaskId"
          columns={this.columns}
          onSelectRow={this.handleSelectRows}
          onChange={this.handleStandardTableChange}
        />
      </div>
    );
    // 已发单
    const employeeCharge = (
      <div>
        <Row style={{ marginBottom: 16 }}>
          <Authorized authority="ns:sendAdd:cancelSend" noMatch={null}>
            <Button type="primary" onClick={this.cancelSend}>
              取消发单
            </Button>
          </Authorized>
          <Authorized authority="ns:sendAdd:export" noMatch={null}>
            <Button
              style={{ marginLeft: '8px' }}
              icon={<DownloadOutlined />}
              onClick={() => {
                this.export();
              }}
            >
              导出
            </Button>
          </Authorized>
        </Row>
        <StandardTable
          selectedRows={sleectedList}
          loading={loading}
          selectedRowKeys={selectedRowKeys}
          data={pageData}
          rowKey="sendOrdAddTaskId"
          columns={this.columnstwo}
          onSelectRow={this.handleSelectRows}
          onChange={this.handleStandardTableChange}
        />
      </div>
    );
    // 已接单
    const supplierCharge = (
      <div>
        <Row style={{ marginBottom: 16 }}>
          <Authorized authority="ns:sendAdd:export" noMatch={null}>
            <Button
              type="primary"
              icon={<DownloadOutlined />}
              onClick={() => {
                this.export();
              }}
            >
              导出
            </Button>
          </Authorized>
        </Row>
        <StandardTable
          selectedRows={sleectedList}
          selectedRowKeys={selectedRowKeys}
          loading={loading}
          data={pageData}
          rowKey="sendOrdAddTaskId"
          columns={this.columnsthree}
          onSelectRow={this.handleSelectRows}
          onChange={this.handleStandardTableChange}
        />
      </div>
    );
    // 已回单
    const retuedReceipt = (
      <div>
        <div style={{ marginBottom: '16px' }}>
          <Authorized authority="ns:sendAdd:export" noMatch={null}>
            <Button
              type="primary"
              icon={<DownloadOutlined />}
              onClick={() => {
                this.export();
              }}
            >
              导出
            </Button>
          </Authorized>
          <div style={{ float: 'right' }}>
            <RadioGroup className={styles.floatRight} value={editFlag} onChange={this.saculo}>
              <RadioButton value={null}>全部</RadioButton>
              <RadioButton value={2}>无修改</RadioButton>
              <RadioButton value={1}>有修改</RadioButton>
            </RadioGroup>
          </div>
        </div>
        <StandardTable
          selectedRows={sleectedList}
          selectedRowKeys={selectedRowKeys}
          loading={loading}
          data={pageData}
          rowKey="sendOrdAddTaskId"
          columns={this.columnsfour}
          onSelectRow={this.handleSelectRows}
          onChange={this.handleStandardTableChange}
        />
      </div>
    );
    // 问题人员
    const problemPeople = (
      <div>
        <div style={{ marginBottom: '16px' }}>
          <Authorized noMatch={null} authority="ns:sndrAddProb:addProbFdbk">
            <Button
              type="primary"
              onClick={() => router.push('/sendordermanage/addemployee/batchfeedback?busiType=11')}
              style={{ marginRight: 8 }}
            >
              批量反馈
            </Button>
          </Authorized>
          <Authorized noMatch={null}>
            <ProExportBtn selectedRowKeys={selectedRowKeys} downloadParams={downloadParams} />
          </Authorized>
        </div>
        {/* <StandardTable
          selectedRows={sleectedList}
          selectedRowKeys={selectedRowKeys}
          loading={loading}
          data={proPageData}
          rowKey="sendOrdAddTaskId"
          columns={this.columnsfive}
          onSelectRow={this.handleSelectRows}
          onChange={this.handleStandardTableChange}
        /> */}
        <ProTable
          onRef={e => {
            this.setState({ proTable: e });
          }}
          selectedRows={sleectedList}
          selectedRowKeys={selectedRowKeys}
          onSelectRow={this.handleSelectRows}
          proUrl="/sendordermanage/addemployee/problem"
          busiType="11"
        />
      </div>
    );
    // 已取消
    const canCelled = (
      <div>
        <StandardTable
          selectedRows={sleectedList}
          selectedRowKeys={selectedRowKeys}
          loading={loading}
          data={pageData}
          rowKey="sendOrdAddTaskId"
          columns={this.columnssix}
          onSelectRow={this.handleSelectRows}
          onChange={this.handleStandardTableChange}
        />
      </div>
    );

    // 获取页签组件
    const getTabPane = key => {
      if (key === '1') {
        return customerCharge;
      }
      if (key === '2') {
        return employeeCharge;
      }
      if (key === '3') {
        return supplierCharge;
      }
      if (key === '4') {
        return retuedReceipt;
      }
      if (key === '5') {
        return problemPeople;
      }
      if (key === '6') {
        return canCelled;
      }
      return <div />;
    };
    return (
      <PageHeaderWrapper>
        <Card className={styles.searchCard}>
          <div className={styles.tableListForm}>{this.renderForm()}</div>
        </Card>
        <Card className={styles.tabCard}>
          <div className={styles.tableList}>
            <Tabs activeKey={activeKey} onChange={this.changeTabPane}>
              {tabList.map(pane => (
                <TabPane tab={<Badge dot={pane.isHas}>{pane.itemName}</Badge>} key={pane.itemCode}>
                  {getTabPane(pane.itemCode)}
                </TabPane>
              ))}
            </Tabs>
          </div>
        </Card>
        <BatchTaskProgress
          progressVisible={progressVisible}
          progressPercent={addempsend.progressPercent}
          isShowResult={isShowResult}
          resultInfo={resultInfo}
          checkHasTask={this.checkHasTask}
          handleProgressModalVisible={this.handleProgressModalVisible}
          maskClosable={false}
        />
      </PageHeaderWrapper>
    );
  }
}

export default TableList;
